package com.sxm.yiwei.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.beans.pinche.HttpHead;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.GetUiltsData;
import com.sxm.yiwei.utils.HandleDataUtil;
import com.sxm.yiwei.views.CenterDialog;

import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;

/**
 * fragment 基类
 */
public abstract class BaseFragment extends Fragment implements GetUiltsData.CallBackUtilsInf{
    protected boolean isInit = false;//视图是否已经初初始化
    protected boolean isLoad = false;//是否加载
    protected final String TAG = "BaseFragment";
    private View view;//视图
    private Toast toast;
    private ProgressDialog progressDialog;
    private CenterDialog centerDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(setContentView(), container, false);
        isInit = true;
        initData();
        /**初始化的时候去加载数据**/
        isCanLoadData();
        return view;
    }

    /**
     * 视图是否可见
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    /**
     * 是否可以加载数据
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            startLoad();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;
    }

    protected View getContentView() {
        return view;
    }

    /**
     * findViewById
     */
    protected <T extends View> T findViewById(int id) {
        return (T) getContentView().findViewById(id);
    }

    protected abstract int setContentView();//显示的布局

    protected abstract void startLoad();//加载数据

    protected abstract void initData();//初始化数据

    /**
     * 当视图不可见并且加载过数据,调用此方法
     */
    protected void stopLoad() {}
    public HttpHead getHeadInfo(){
        SharedPreferences sp=getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        //Log.d("getHeadInfo",sp.getString("appid",""));
        return new HttpHead(sp.getString("token",""),sp.getString("appid",""),sp.getString("userId",""),"application/json");
    }
    public void showToast(String text) {
        if (toast == null) {
            toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        } else {
            toast.setText(text);
        }
        toast.show();
    }

    public void httpPost(Context context,String url, JSONObject object, String fromWhere){
        progressDialog = ProgressDialog.show(context,"加载","正在加载中...");
        GetUiltsData.xPostMethod(getParamsPost(url,object),context,this,fromWhere);
    }
    public void httpGet(Context context,String url, JSONObject object, String fromWhere){
        progressDialog = ProgressDialog.show(context,"加载","正在加载中...");
        GetUiltsData.xGetMethod(getParamsGet(url,object),context,this,fromWhere);
    }
    private RequestParams getParamsPost(String url, JSONObject object){
        RequestParams params = new RequestParams(url);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",getHeadInfo().getToken());
        params.addHeader("appId",getHeadInfo().getAppId());
        params.addHeader("userId",getHeadInfo().getUserId());
        params.setBodyContent(object.toJSONString());
        return params;
    }
    private RequestParams getParamsGet(String url, JSONObject object){
        RequestParams params = new RequestParams(url);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",getHeadInfo().getToken());
        params.addHeader("appId",getHeadInfo().getAppId());
        params.addHeader("userId",getHeadInfo().getUserId());
        params.addParameter("params",object.toJSONString());
        return params;
    }

    @Override
    public void onSuccess(String result, String fromWhere) {
        progressDialog.dismiss();
        HandleDataUtil.show(fromWhere,result);
        //Log.d(fromWhere,result);
    }

    @Override
    public void onSuccessError(String result, String fromWhere) {
        progressDialog.dismiss();
        Log.d(fromWhere,result);
        JSONObject object = JSON.parseObject(result);
        String status = object.getString("status");
        if (!status.equals("1")){
            String failure = object.getString("failure");
            Log.d("failure",failure);
            showToast("failure="+failure);
            if (failure.equals("1082")){
                showToast("订单已超时");
                //CAN_NOT_END_THE_ROUTE("1086");
            }else if (failure.equals("1086")){
                showToast("乘客还未上车,您无法结束行程");
            }else if (failure.equals("1087")){
                showToast("已过出发时间");
            }
        }
    }

    @Override
    public void onError(Throwable ex) {
        progressDialog.dismiss();
        showToast(ex.toString());
        Log.d("onError",ex.toString());
        if (ex instanceof HttpException){
            showToast("服务器链接断开");
        }else {

        }
    }


}
